import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/Navbar'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { getToken } from '@/utils/storage.js'
import io from 'socket.io-client'
import { getMineInfo } from '@/store/actions/mine'

const Chat = () => {
    const history = useHistory()
    const [chartList, setChartList] = useState([
        { type: 'robot', message: '欢迎你' },
        { type: 'user', message: '你好' }])
    const photo = useSelector(state => state.mine.user.photo)
    const socketRef = useRef(null)
    const chartListRef = useRef(null)
    const dispatch = useDispatch()
    useEffect(() => {
        dispatch(getMineInfo())
        const socket = io('http://toutiao.itheima.net', {
            query: {
                token: getToken().token
            },
            transports: ['websocket']
        })
        socketRef.current = socket
        socket.on('connect', () => {
            setChartList((chartList) =>
                [...chartList, { type: 'robot', message: '您已连接成功,开始聊天吧' }]
            )
        })
        socket.on('message', (e) => {
            setChartList((chartList) =>
                [...chartList, { type: 'robot', message: e.msg }]
            )
        })
        return () => {
            socket.close()
        }
    }, [dispatch])

    // 输入框
    const [msg, setMsg] = useState('')
    // 输入框发送消息
    const onSubmit = (e) => {
        if (e.keyCode !== 13) return
        if (!msg) return
        socketRef.current.emit('message', {
            msg,
            timestamp: Date.now()
        })
        setChartList([
            ...chartList, { type: 'user', message: msg }
        ])
        setMsg('')
    }

    // 获取和发送消息时滚动最下方
    useEffect(() => {
        chartListRef.current.scrollTop = chartListRef.current.scrollHeight
    }, [chartList])

    return (
        <div className={styles.root}>
            {/* 顶部导航栏 */}
            <NavBar className="fixed-header" onLeftClick={() => history.go(-1)}>
                小智同学
            </NavBar>

            {/* 聊天记录列表 */}
            <div className="chat-list" ref={chartListRef}>
                {chartList.map((item, index) => {
                    if (item.type === 'robot') {
                        return (<div className="chat-item" key={index}>
                            <Icon type="iconbtn_xiaozhitongxue" />
                            <div className="message">{item.message}</div>
                        </div>)
                    }
                    else {
                        return (<div className="chat-item user" key={index}>
                            <img src={photo} alt="" />
                            <div className="message">{item.message}</div>
                        </div>)
                    }
                })}



            </div>

            {/* 底部消息输入框 */}
            <div className="input-footer">
                <Input
                    className="no-border"
                    placeholder="请描述您的问题"
                    value={msg}
                    onChange={e => setMsg(e.target.value)}
                    onKeyUp={e => onSubmit(e)}
                />
                <Icon type="iconbianji" />
            </div>
        </div>
    )
}

export default Chat